package book;

import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.lcdui.Graphics;

import screen.Repaintable;
import utils.Screen;

public class ProgressivePhraseFaderImpl implements PhraseFader {

	private static final int NUM_FADE_STEP = 5;

	private Repaintable bookScreen;
	private boolean isFadeInprogress;
	private boolean isNewSetup;
	private int lineIndex;
	private int fadeMode;
	private String[] phraseChunks;
	private int[] fadeSteps;
	private boolean[] isFadeStarted;

	public ProgressivePhraseFaderImpl(Repaintable aBookScreen) {
		bookScreen = aBookScreen;
		isFadeInprogress = false;
	}

	public boolean isFadeInprogress() {
		return isFadeInprogress;
	}

	public void repaint(Graphics g) {
		if (isNewSetup) {
			isFadeInprogress = true;
			isNewSetup = false;
		}
		if (!isFadeInprogress) {
			return;
		}
		if (fadeMode == DOWNWARDS) {

		} else if (fadeMode == UPWARDS) {
			repaintUpwards(g);
		}
	}

	private void repaintUpwards(Graphics g) {

		for (int i = 0; i < phraseChunks.length; i++) {
			int currentColor = getColor(i);
			g.setColor(currentColor);
			g.drawString(phraseChunks[i], Screen.SIDE_MARGIN,
					Screen.BLACK_TOP_HEIGHT + Screen.SIDE_MARGIN 
					+ g.getFont().getHeight()
					* (lineIndex + i), Graphics.LEFT | Graphics.TOP);
			if ((isFadeStarted[i]) && (fadeSteps[i] < NUM_FADE_STEP - 1)) {				
				fadeSteps[i]++;
			}
		}

		if (fadeSteps[fadeSteps.length - 1] <= NUM_FADE_STEP) {
			// 1,2 secondes pour repeindre
			new Timer().schedule(new TimerTask() {
				public void run() {
					bookScreen.repaint();
				}
			}, 1200 / NUM_FADE_STEP);
		} else {
			isFadeInprogress = false;
		}
	}

	private int getColor(int index) {
		int result = 0xFFFFFF;
		int[] grayScale = new int[] {0xCCCCCC,
				0x888888, 0x444444, 0x222222, 0x111111 };

		if (isFadeStarted[index]) {
			result = grayScale[fadeSteps[index]];
		}
		return result;
	}

	public void setupFading(String[] somePhraseChuncks, int aLineIndex,
			int aFadeMode) {
		isNewSetup = true;
		phraseChunks = somePhraseChuncks;
		lineIndex = aLineIndex;
		fadeMode = aFadeMode;
		int length = phraseChunks.length;
		fadeSteps = new int[length];
		isFadeStarted = new boolean[length];
		
		for (int i = 0; i < fadeSteps.length; i++) {
			fadeSteps[i] = 0;
			isFadeStarted[i] = false;
			new Timer().schedule(new StartTimer(i), 400*i);
		}
	}
	
	private class StartTimer extends TimerTask {

		private int index;
		
		public StartTimer(int anIndex) {
			index = anIndex;
		}
		
		public void run() {
			isFadeStarted[index] = true;
		}
	}

	public void blackRepaint(Graphics g) {
		g.setColor(0x111111);
		for (int i = 0; i < phraseChunks.length; i++) {
			g.drawString(phraseChunks[i], Screen.SIDE_MARGIN,
					Screen.BLACK_TOP_HEIGHT 
					+ Screen.SIDE_MARGIN + g.getFont().getHeight()
					* (lineIndex + i), Graphics.LEFT | Graphics.TOP);
		}
	}

}
